# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :send_sms.py
# @Time      :2022/6/29 10:57
# @Author    :吕华龙
from ronglian_sms_sdk import SmsSDK
from flask import current_app
import json
import redis


class SendSMS:
    sdk = None
    rds = None

    def __init__(self):
        accId = current_app.config["ACCOUNT_SID"]
        accToken = current_app.config["AUTH_TOKEN"]
        appId = current_app.config["APPID"]
        self.sdk = SmsSDK(accId, accToken, appId)
        self.rds = redis.Redis(host=current_app.config["REDIS_HOST"], port=current_app.config["REDIS_PORT"],
                               password=current_app.config["REDIS_PASSWORD"])

    def send_sms(self, mobile, datas):
        """
        发送短信验证码
        :param mobile:   手机号
        :param datas:   模板参数，元组
        :return:  bool
        """
        tid = current_app.config["TID"]
        # 【云通讯】您的验证码是{1},请于{2}分钟内正确输入
        resp = self.sdk.sendMessage(tid, mobile, datas)  # resp的类型是字符串
        # 解析json字符串
        resp = json.loads(resp)
        print("-----------------------------", resp)
        # 存到redis
        key = "sms_" + mobile
        self.rds.set(key, datas[0], ex=int(datas[1]) * 60)

        if resp['statusCode'] == "000000":
            return True
        else:
            return False

        # print("-------------", tid)
        # print(type(tid))

    def ver_code(self, mobile, code):
        """
        校验验证码
        :param mobile:   手机号
        :param code:    验证码
        :return:
        """
        key = "sms_" + mobile
        res = self.rds.get(key)  # 返回值是字节类型或None
        print(res)

        if not res:
            return False

        sys_code = res.decode()
        print("---", sys_code)
        print("======", code)
        if sys_code != code[0]:
            return False
        else:
            return True


if __name__ == '__main__':
    from app import app

    with app.app_context():
        s = SendSMS()
        # 发送验证码
        r = s.send_sms("17631580690", ("6666", "5"))
        # 校验验证码
        # r = s.ver_code("17631580690", ("6666", "5"))
        print(r)
        # r = s.send_sms("13112345678", ("9999", "5"))
        # print(r)

# from ronglian_sms_sdk import SmsSDK
#
# accId = '8aaf07087bc82708017bf7ea668d0f19'
# accToken = '421d07d3905c401c86649006f7a6b033'
# appId = '8aaf07087bc82708017bf7ea68910f20'
#
#
# def send_message(mobile, code):
#     tid = '1'
#
#     datas = (code, '3')
#     resp = SmsSDK(accId, accToken, appId).sendMessage(tid, mobile, datas)
#     return resp
